import { generateSvgContent, generateSvgsHtmlContent } from "./templates";
import { checkAndMakeDirPath, getIconfontContent } from "./tools";
import { IOptions, ISvgOptions } from "./types";

const fs = require("fs");
const path = require("path");

export function restoreSvgs(options: IOptions) {
  options.outputValue = options.outputValue || "/dist";
  const { inputValue, restore } = options;
  if (typeof inputValue !== "string") {
    throw new Error("input must be a string");
  }
  if (!inputValue.endsWith(".js")) {
    throw new Error("input must be a .js file");
  }
  const restoreSymbols =
    typeof restore === "string" ? restore.split(",").filter(Boolean) : [];
  const inputPathList: string[] = (inputValue || "").split("/").filter(Boolean);
  const inputPath = path.join(process.cwd(), ...inputPathList);
  if (!fs.existsSync(inputPath) || !fs.statSync(inputPath).isFile()) {
    throw new Error(`Input path ${inputPath} does not exist or is not a file`);
  }
  // 读取iconfont文件，生成svg文件内容
  const { svgList } = getIconfontContent(inputPath);
  // 输出文件
  outputSvgs(svgList, restoreSymbols, options);
}

// 输出svg文件到指定目录
function outputSvgs(
  svgList: ISvgOptions[],
  restoreSymbols: string[],
  options: IOptions
) {
  const { outputValue } = options;
  const outputPathList: string[] =
    outputValue?.split("/").filter(Boolean) || [];
  const outputPath = path.join(process.cwd(), ...outputPathList);
  // 生成输出目录
  checkAndMakeDirPath(outputPath);
  if (Array.isArray(svgList) && svgList.length) {
    // 所有的svgId
    const allSvgIds = svgList.map((svg) => svg.name);
    const restoreMap: any = (
      restoreSymbols.length > 0 ? restoreSymbols : allSvgIds
    ).reduce((p, c) => {
      p[c] = true;
      return p;
    }, {} as any);
    // 最终要恢复的svg文件
    const resultSvgList = svgList.filter((item) => restoreMap[item.name]);
    resultSvgList.forEach((svg) => {
      const { content, name, viewBox } = svg;
      const svgPath = path.join(outputPath, `${name}.svg`);
      fs.writeFileSync(svgPath, generateSvgContent(content, viewBox));
    });
    // 生成hmtl预览
    if (resultSvgList.length) {
      fs.writeFileSync(
        path.join(outputPath, "index.html"),
        generateSvgsHtmlContent(resultSvgList.map((item) => item.name))
      );
    }
  }
}
